package com.glsc.ngateway.ldap.utils;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*
 * 构造及解析jwt的工具类
 */
public class JwtHelper {

    private static final String SECRET = "glsc9557@dsDSAwqeDSA31dsad23dqweu3210ofun32dm76ngr";

    public static String generateToken(String username) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);
        String jwt = Jwts.builder()
                .setClaims(map)
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 2))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        return jwt;
    }

    public static String parseToken(String token) {
        try {
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
            return (String) body.get("username");
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        String longTimeToken = generateToken("devadmin");
    }
}
